package com.wzdigit.wms.raw.service.backtosap;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.enums.writeback.OtherSystemEnum;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mapping.CodeMappingMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.raw.client.response.gdn.delivery.DeliveryGoodsResponse;
import com.wzdigit.wms.raw.client.response.gdn.delivery.SimpleGdnDtl;
import com.wzdigit.wms.raw.domain.mid.PoDtl;
import com.wzdigit.wms.raw.domain.mid.PoHeader;
import com.wzdigit.wms.raw.service.mid.IfPostbackService;
import com.wzdigit.wms.web.service.wms2sap.outstore.ZDT_071_ReqCDK;
import com.wzdigit.wms.web.service.wms2sap.purchaseorder.ZDT_069_ReqRECORDS;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
    * 采购订单回写
    * @author shuaic
    * @date 2021/6/18 17:54
*/
@Service
@Slf4j
public class PurchaseOrderBackService {
    @Autowired
    IfPostbackService ifPostbackService ;

    @Autowired
    private CodeMappingService codeMappingService;

    @Autowired
    SkuMapper skuMapper ;

    @Autowired
    CodeMappingMapper codeMappingMapper ;

    @Autowired
    WarehouseMapper warehouseMapper ;
    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi basicVendorApi;
    /**
     * @param header 出库单主表
     * @param dtlCollectMap 出库单明细分组
     * @param goodsCollectMap  出库单明细SN
     * @return void
     * @author shuaic
     * @date 2021/8/10 23:08
     */
    public void gdnWriteBackToSap(GdnHeader header, Map<BigDecimal, List<SimpleGdnDtl>> dtlCollectMap, Map<BigDecimal, List<DeliveryGoodsResponse>> goodsCollectMap,String type) {
        //查询供应商
        String  vendorCode = "";
        if(header.getConsigneeId()!=null){
            VendorDTO vendor = basicVendorApi.getVendorById(header.getConsigneeId().intValue());
            if(vendor!=null||vendor.getVendorCode()!=null){
                vendorCode = vendor.getVendorCode();
            }
        }


        //回写数据集合
        List<ZDT_069_ReqRECORDS>  list = new ArrayList<>();
        for (Map.Entry<BigDecimal, List<SimpleGdnDtl>> entry : dtlCollectMap.entrySet()) {
            BigDecimal key = entry.getKey();//明细ID
            SimpleGdnDtl dtl = entry.getValue().get(0);//出库单明细
            //获取明细交货数量
            ZDT_069_ReqRECORDS record = new ZDT_069_ReqRECORDS();
            //转换单据类型TODO
            record.setDOCTP(type);//单据类型? 1退货采购订单 2公司间退货
            record.setEBELN(header.getGdnNo());//单号
            record.setEBELP(dtl.getSourceShipNoticeItem()+"");//单据原来的行号
            Sku sku = skuMapper.selectById(dtl.getSkuId());
            if(sku==null){
                String message = String.format("未找到ID为【%s】的SKU信息",dtl.getSkuId());
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }
            record.setMATNR(sku.getSkuCode());//物料
            record.setMENGE(dtl.getOrderQty()+"");//数量
            //查询仓库
            Warehouse warehouse = warehouseMapper.selectById(dtl.getWhsId());
            CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(header.getFactory(), warehouse.getWhsCode(), dtl.getQaStatus());
            record.setLGORT(codeMapping.getMappingCode());//库存地点 仓库
            record.setERNAM(header.getGdnCreateUser());//WMS审核人
            record.setBUDAT(DateUtil.format(new Date(),"yyyyMMdd"));//过帐日期
            record.setLGORT(codeMapping.getMappingCode());//对方仓库编码


            list.add(record);


        }

        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackNo(header.getGdnNo());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_PURCHASE_ORDER.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }
    }



    /*  采购订单同步GDN 公司间退货(感觉是)
     * @param header 表头
     * @param dtl 明细
     * @return boolean
     * @author shuaic
     * @date 2021/6/18 9:57
     */
    public  void purchaseOrderWriteBack(GdnHeader header, List<GdnDtl> dtlList ){
        //生成回写数据
        List<ZDT_069_ReqRECORDS>  list = new ArrayList<>();
        for(GdnDtl dtl  : dtlList){
            ZDT_069_ReqRECORDS record = new ZDT_069_ReqRECORDS();
            Sku sku = skuMapper.selectById(dtl.getSkuId());
            if(sku==null){
                String message = String.format("未找到ID为【%s】的SKU信息",dtl.getSkuId());
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }

            //查询仓库
            Warehouse warehouse = warehouseMapper.selectById(dtl.getWhsId());
            CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(header.getFactory(), warehouse.getWhsCode(), 0);
            //TODO
            record.setDOCTP("2"); //单据类型? 1退货采购订单 2公司间退货
            record.setEBELN(header.getGdnNo());//单号
            record.setEBELP(dtl.getGdnLineNo()+"");//行号
            record.setMATNR(sku.getSkuCode());//物料
            record.setMENGE(dtl.getOrderQty()+"");//数量
            record.setLGORT(codeMapping.getMappingCode());//库存地点 仓库
            record.setERNAM(header.getGdnApprovedUser());//WMS审核人
            record.setBUDAT(DateUtil.format(header.getGdnApprovedTime(),"yyyyMMdd"));//过帐日期
            record.setLGORT(codeMapping.getMappingCode());//对方仓库编码
            list.add(record);
        }
        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_PURCHASE_ORDER.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }

    }

    /*  采购订单同步PO  1退货采购订单
     * @param header 表头
     * @param dtl 明细
     * @return boolean
     * @author shuaic
     * @date 2021/6/18 9:57
     */
    public  void purchaseOrderWriteBack(PoHeader header, List<PoDtl> dtlList ){
        //生成回写数据
        List<ZDT_069_ReqRECORDS>  list = new ArrayList<>();
        for(PoDtl dtl  : dtlList){
            ZDT_069_ReqRECORDS record = new ZDT_069_ReqRECORDS();
            Sku sku = skuMapper.selectById(dtl.getSkuId());
            if(sku==null){
                String message = String.format("未找到ID为【%s】的SKU信息",dtl.getSkuId());
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }

            //查询仓库
            Warehouse warehouse = warehouseMapper.selectById(dtl.getWhsId());
            CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(header.getFactory(), warehouse.getWhsCode(), null);
            //TODO
            record.setDOCTP("2"); //单据类型? 1退货采购订单 2公司间退货
            record.setEBELN(header.getPoNo());//单号
            record.setEBELP(dtl.getPoLineNo()+"");//行号
            record.setMATNR(sku.getSkuCode());//物料
            record.setMENGE(dtl.getOrderQty()+"");//数量
            record.setLGORT(codeMapping.getMappingCode());//库存地点 仓库
            //TODO
            record.setERNAM("system");//WMS审核人
            //TODO
            record.setBUDAT(DateUtil.format(new Date(),"yyyyMMdd"));//过帐日期
            record.setLGORT(codeMapping.getMappingCode());//对方仓库编码
            list.add(record);
        }
        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_PURCHASE_ORDER.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }

    }

}
